package com.example.studyktdemo.ui.fragment

import android.graphics.Rect
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.example.studyktdemo.R
import com.example.studyktdemo.adapter.CategoryAdapter
import com.example.studyktdemo.base.BaseFragment
import com.example.studyktdemo.databinding.FragmentCategoryBinding
import com.example.studyktdemo.uitls.ARouterUtil
import com.example.studyktdemo.viewmodel.CategoryViewModel

class CategoryFragment : BaseFragment<FragmentCategoryBinding>() {

    private var viewModel = CategoryViewModel()

    private var gridLayoutManager = GridLayoutManager(context, 2)
    private lateinit var categoryAdapter: CategoryAdapter

    companion object {
        fun getInstance(): CategoryFragment {
            val instance = CategoryFragment()

            return instance
        }
    }

    override fun initView() {
        viewModel = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        )[viewModel::class.java]

        binding.categoryRv.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                outRect.top = 20
                outRect.left = 10
                outRect.right = 10
            }
        })
    }

    override fun initData() {
        viewModel.queryCategoryList()
        categoryAdapter = CategoryAdapter()
        binding.categoryRv.adapter = categoryAdapter
        binding.categoryRv.layoutManager = gridLayoutManager
    }

    override fun initObserver() {
        viewModel.categoryMutableLiveData.observe(this, { categoryList ->
            if (categoryList != null) {
                categoryAdapter.setData(categoryList)
            }
        })
    }

    override fun initListener() {
        categoryAdapter.setCategoryItemClick(object :CategoryAdapter.CategoryItemClick{
            override fun itemClick() {
                Toast.makeText(context,"点击了",Toast.LENGTH_SHORT).show()
                ARouter.getInstance().build(ARouterUtil.CATEGORY_DETAIL_ACTIVITY).navigation()
            }
        })
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_category
    }
}